package com.dsideal.cloud.cas.client.manager;

import com.dsideal.cloud.cas.client.config.MysqlConfig;
import com.dsideal.cloud.cas.client.constant.LoginConstants;
import com.dsideal.cloud.cas.client.dto.UserDetailsDTO;
import com.dsideal.cloud.cas.client.entity.UserLog;
import com.dsideal.cloud.cas.client.utils.JWTInfoForCas;
import com.dsideal.cloud.cas.client.utils.JwtTokenUtil;
import com.dsideal.cloud.common.entity.Roles;
import com.dsideal.cloud.common.util.DateUtils;
import com.dsideal.cloud.common.util.IpUtils;
import com.dsideal.cloud.common.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class LoginManager {

    @Autowired
    public MysqlConfig jdbcTemplete;

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    /**
     * 用户认证通过之后，查询用户信息
     * @param username
     * @return
     */
    public UserDetailsDTO extendUserInfo(String username) {
        List<Map<String,Object>> userAndRoleList = jdbcTemplete.queryByname(username);

        if(CollectionUtils.isEmpty(userAndRoleList)){
            return null;
        }
        String userId = Optional.ofNullable(userAndRoleList.get(0).get("base_user_id")).orElse(StringUtils.EMPTY).toString();
        String buId = Optional.ofNullable(userAndRoleList.get(0).get("bureau_id")).orElse(StringUtils.EMPTY).toString();
        List<Roles> roles = new ArrayList<>();
        userAndRoleList.forEach(i ->
                roles.add(
                        Roles.builder()
                                .roleId(Optional.ofNullable(i.get("base_role_id")).orElse(StringUtils.EMPTY).toString())
                                .dataScope(Optional.ofNullable(i.get("data_scope")).orElse(StringUtils.EMPTY).toString())
                                .roleCode(Optional.ofNullable(i.get("role_code")).orElse(StringUtils.EMPTY).toString())
                                .build()
                )
        );
        return UserDetailsDTO.builder()
                .userId(userId)
                .buId(buId)
                .roles(roles)
                .build();
    }

    /**
     * 用户认证通过之后，查询用户信息
     * @param yjUserId
     * @return
     */
    public UserDetailsDTO extendUserInfoById(String yjUserId) {
        List<Map<String,Object>> userAndRoleList = jdbcTemplete.queryById(yjUserId);
        if (CollectionUtils.isNotEmpty(userAndRoleList)) {
            String userId = Optional.ofNullable(userAndRoleList.get(0).get("base_user_id")).orElse(StringUtils.EMPTY).toString();
            String buId = Optional.ofNullable(userAndRoleList.get(0).get("bureau_id")).orElse(StringUtils.EMPTY).toString();
            List<Roles> roles = new ArrayList<>();
            userAndRoleList.forEach(i ->
                    roles.add(
                            Roles.builder()
                                    .roleId(Optional.ofNullable(i.get("base_role_id")).orElse(StringUtils.EMPTY).toString())
                                    .dataScope(Optional.ofNullable(i.get("data_scope")).orElse(StringUtils.EMPTY).toString())
                                    .roleCode(Optional.ofNullable(i.get("role_code")).orElse(StringUtils.EMPTY).toString())
                                    .build()
                    )
            );
            return UserDetailsDTO.builder()
                    .userId(userId)
                    .buId(buId)
                    .roles(roles)
                    .build();
        }

        return null;
    }

    /**
     * 用户认证通过之后，查询用户信息
     * @param yjUserId
     * @return
     */
    public UserDetailsDTO extendUserInfoById2(String yjUserId) {
        List<Map<String,Object>> userAndRoleList = jdbcTemplete.queryById2(yjUserId);
        if (CollectionUtils.isNotEmpty(userAndRoleList)) {
            String userId = Optional.ofNullable(userAndRoleList.get(0).get("base_user_id")).orElse(StringUtils.EMPTY).toString();
            String buId = Optional.ofNullable(userAndRoleList.get(0).get("bureau_id")).orElse(StringUtils.EMPTY).toString();
            List<Roles> roles = new ArrayList<>();
            userAndRoleList.forEach(i ->
                    roles.add(
                            Roles.builder()
                                    .roleId(Optional.ofNullable(i.get("base_role_id")).orElse(StringUtils.EMPTY).toString())
                                    .dataScope(Optional.ofNullable(i.get("data_scope")).orElse(StringUtils.EMPTY).toString())
                                    .roleCode(Optional.ofNullable(i.get("role_code")).orElse(StringUtils.EMPTY).toString())
                                    .build()
                    )
            );
            return UserDetailsDTO.builder()
                    .userId(userId)
                    .buId(buId)
                    .roles(roles)
                    .build();
        }

        return null;
    }

    public void updateUserYjToken(String yjUserId, String yjToken) {
        jdbcTemplete.updateUserYjToken(yjUserId, yjToken);
    }

    public void updateUserYjToken(String yjUserId, String yjToken, String yjRoleIds) {
        jdbcTemplete.updateUserYjToken(yjUserId, yjToken, yjRoleIds);
    }

    public String createToken(UserDetailsDTO userDetailsDTO, String ua) {
        JWTInfoForCas jwtInfoForCas = new JWTInfoForCas(null, userDetailsDTO.getUserId(), null, ua, userDetailsDTO.getRoles(), userDetailsDTO.getBuId());
        return jwtTokenUtil.generateToken(jwtInfoForCas);
    }


    /**
     * 用户登录，记录用户登录日志信息
     * @return
     */
    //@Async
    public void insertUserLog(UserLog userLog) {
        String userId = userLog.getBaseUserId();

        //查询用户pb身份信息
        Map<String, Object> identityMap = jdbcTemplete.queryIdentity(userId);
        String identityCode = Optional.ofNullable(identityMap.get("identity_code")).orElse(StringUtils.EMPTY).toString();
        //教师
        if(LoginConstants.IdentityCode.TEACHER.getCode().equals(identityCode)){
            //查询用户当前学期任课信息
            List<Map<String,Object>> userTeachPlanList = jdbcTemplete.queryTeachPlan(userId);
            String stageCode = String.join("、", userTeachPlanList.stream()
                    .map(m -> Optional.ofNullable(m.get("business_stage_code")).orElse(StringUtils.EMPTY).toString())
                    .distinct().collect(Collectors.toList()));
            String stageName = String.join("、", userTeachPlanList.stream()
                    .map(m -> Optional.ofNullable(m.get("stage_name")).orElse(StringUtils.EMPTY).toString())
                    .distinct().collect(Collectors.toList()));
            String subjectCode = String.join("、", userTeachPlanList.stream()
                    .map(m -> Optional.ofNullable(m.get("business_subject_code")).orElse(StringUtils.EMPTY).toString())
                    .distinct().collect(Collectors.toList()));
            String subjectName = String.join("、", userTeachPlanList.stream()
                    .map(m -> Optional.ofNullable(m.get("subject_name")).orElse(StringUtils.EMPTY).toString())
                    .distinct().collect(Collectors.toList()));
            //查询教师信息
            UserLog userLogTeacherInfo = jdbcTemplete.queryTeacherInfo(userId);
            userLogTeacherInfo.setStageCode(stageCode);
            userLogTeacherInfo.setStageName(stageName);
            userLogTeacherInfo.setSubjectCode(subjectCode);
            userLogTeacherInfo.setSubjectName(subjectName);
            userLogTeacherInfo.setLoginIp(userLog.getLoginIp());
            userLogTeacherInfo.setLoginType(userLog.getLoginType());
            userLogTeacherInfo.setAccountType(userLog.getAccountType());
            userLogTeacherInfo.setEquipmentType(userLog.getEquipmentType());
            userLogTeacherInfo.setLoginResult(userLog.getLoginResult());
            userLogTeacherInfo.setLoginRemark(userLog.getLoginRemark());
            userLogTeacherInfo.setBureauStage(LoginConstants.STAGE_CODE_MAP.get(userLogTeacherInfo.getBureauStage()));
            userLogTeacherInfo.setBaseUserLogId(UUIDUtils.generate32Uuid());
            userLogTeacherInfo.setCreateTime(userLog.getCreateTime());
            int result = jdbcTemplete.insertUserLog(userLogTeacherInfo);
            if (result < 1){
                log.error("================记录登录日志失败================",userLogTeacherInfo);
            }
        }
        //学生
        if(LoginConstants.IdentityCode.STUDENT.getCode().equals(identityCode)){
            //查询学生信息
            UserLog userLogStudentInfo = jdbcTemplete.queryStudentInfo(userId);
            userLogStudentInfo.setLoginIp(userLog.getLoginIp());
            userLogStudentInfo.setLoginType(userLog.getLoginType());
            userLogStudentInfo.setAccountType(userLog.getAccountType());
            userLogStudentInfo.setEquipmentType(userLog.getEquipmentType());
            userLogStudentInfo.setLoginResult(userLog.getLoginResult());
            userLogStudentInfo.setLoginRemark(userLog.getLoginRemark());
            userLogStudentInfo.setBureauStage(LoginConstants.STAGE_CODE_MAP.get(userLogStudentInfo.getBureauStage()));
            userLogStudentInfo.setBaseUserLogId(UUIDUtils.generate32Uuid());
            userLogStudentInfo.setCreateTime(userLog.getCreateTime());
            int result = jdbcTemplete.insertUserLog(userLogStudentInfo);
            if (result < 1){
                log.error("================记录登录日志失败================",userLogStudentInfo);
            }
        }

    }

    /**
     * @return
     */
    public List< Map<String, Object>> login() {
        return jdbcTemplete.queryLogin();
    }

}
